package gui;

import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JOptionPane;
import function.Function;
import function.Parser;

public class Draw extends Canvas {
	private static final long serialVersionUID = 1L;
	private double a, b, x0, y0, scale;
	private Function f;

	double f(double i) throws Exception {
		return f.evaluate(i);
	}

	public Draw(int w, int h, double a, double b, String fx) throws Exception {
		f = Parser.toFunction(fx);
		x0 = w / 2;
		y0 = h / 2;
		this.a = a <= 0 || a > 300 ? 10 : a;
		this.b = b > 300 || b <= 0 ? 10 : b;
		scale = w / (500);
		setBackground(Color.white);
	}

	public void paint(Graphics d) {
		x0 = getWidth() / 2;
		y0 = getHeight() / 2;
		scale = getWidth() / (500);
		Graphics2D g = (Graphics2D) d;
		g.setColor(Color.red);
		g.draw(new Line2D.Double(0, y0, getWidth(), y0));
		g.draw(new Line2D.Double(x0, 0, x0, getHeight()));
		g.setStroke(new BasicStroke(2));
		g.setColor(Color.blue);
		for (int i = 0; i < 500; i++) {
			try {
				g.draw(new Line2D.Double((x0 + (scale * i) * a), (y0 - f(i
						* scale)
						* b), (x0 + ((i + 1) * scale) * a),
						(y0 - f(((i + 1) * scale)) * b)));
				g.draw(new Line2D.Double((x0 + (scale * -i) * a), (y0 - f(-i
						* scale)
						* b), (x0 + (-1 * (i + 1) * scale) * a), (y0 - f((-1
						* (i + 1) * scale))
						* b)));
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(null, ex.getMessage());
			}

			try {
				Thread.sleep(5);
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(null, ex.getMessage());
			}
		}
	}
}
